package com.iyue.portal;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionRedirect;

import com.iyue.SpringHelper;
import com.iyue.activity.pojo.ActivityAreaCategory;
import com.iyue.activity.pojo.ActivityInfo;
import com.iyue.activity.service.ActivityBiz;
import com.iyue.core.pojo.UserAccount;
import com.iyue.core.service.CoreBiz;
import com.iyue.framework.BaseAction;
import com.iyue.framework.cache.IMemcachedCache;
import com.iyue.framework.util.Pager;
import com.iyue.framework.util.PagerHelper;
import com.iyue.portal.helper.PortalUtil;
import com.iyue.servlet.taglibs.Functions;
import com.iyue.sso.helper.CookieUtil;
import com.iyue.sso.helper.SSOUtil;
import com.iyue.sys.pojo.SysProvince;
import com.iyue.user.helper.UserFunctions;
import com.iyue.user.pojo.UserBasic;
import com.iyue.user.service.UserBiz;
import com.iyue.util.ValidCode;
import com.iyue.util.sns.SnsUtil;

/**
 * 《网站入口》实现类
 *
 * @author 孙晓晔
 * @version $Id: Portal.java,v 1.2 2011/01/05 09:24:31 fresh Exp $
 */
public class Portal extends PortalUtil {

	/*
	 * 网站首页
	 */
	public ActionForward layout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		UserBasic user = user(request);
		request.setAttribute("cuser", user);
		StringBuffer p3 = new StringBuffer();
		String category = request.getParameter("cid");
		if (!StringUtils.isBlank(category) && StringUtils.isNumeric(category)) {
			p3.append("&amp;cid=");
			p3.append(category);
		}

		String ex = request.getParameter("expire");
		if (StringUtils.isBlank(ex)) {
			ex = ActivityInfo.EXPIRE_OFF;
		}

		p3.append("&amp;expire=" + ex);

		String city = "0";
		Integer username = u(request);
		if (username != null) {
			UserBasic basic = UserFunctions.user(username.toString());
			if (basic != null) {
				city = basic.getCity();
				if (!StringUtils.isBlank(city)) {
					p3.append("&amp;city=");
					p3.append(city);
					request.setAttribute("city", city);
				}
			}
		}

		request.setAttribute("p3", p3.toString());

		ActivityBiz biz = (ActivityBiz) SpringHelper.getBean("ActivityBiz");

		int totalRows = 0;
		String s = request.getParameter("n");
		if (s != null && !"".equals(s)) {
			totalRows = Integer.parseInt(s);
		} else {
			totalRows = biz.getCountByCC(city, category, ex);
		}

		if (totalRows == 0) {
			return action.display(request, response, "layout");
		}

		Pager pager = PagerHelper.getPager(request, totalRows, 10);

		List<ActivityAreaCategory> result = biz.getMActivityByCc(city,
				category, ex, pager);

		request.setAttribute("result", result);
		request.setAttribute("pager", pager);
		request.setAttribute("baseLink", "&amp;do=Portal.layout");
       // hangl add
		List<SysProvince> province = Functions.provinces();
		request.setAttribute("provinces", province);
        List cities = Functions.getCities();
        request.setAttribute("cities", cities);
		return action.display(request, response, "layout");
	}

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		if (!isLogin(request)) {
			return action.display(request, response, "login");
		}

		return action.display(request, response, "login");
	}

	/*
	 * 登录
	 */
	public ActionForward loginPost(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		String account = request.getParameter("username");
		if (account == null || "".equals(account.trim())) {
			request.setAttribute("msg", "请输入账号");
			return action.display(request, response, "login");
		}

		String password = request.getParameter("password");
		if (password == null || "".equals(password.trim())) {
			request.setAttribute("msg", "请输入密码");
			return action.display(request, response, "login");
		}

		String code = request.getParameter("vcode");
		if (code == null || code.length() <= 0) {
			request.setAttribute("msg", "验证码不正确！");
			return action.display(request, response, "login");
		}

		String vkey = request.getParameter("vkey");
		if (vkey == null || vkey.length() <= 0) {
			request.setAttribute("msg", "验证码不正确！");
			return action.display(request, response, "login");
		}

		if (!ValidCode.isValid(vkey, code)) {
			request.setAttribute("msg", "验证码不正确！");
			return action.display(request, response, "login");
		}

		if (passwd_fail(account) > 3) {
			request.setAttribute("msg", "您以多次输入密码错误，请2小时后再试！");
			return action.display(request, response, "info");
		}

		Integer result = SnsUtil.login(request, response, account, password);
		if (result.equals(SSOUtil.LOGIN_RUO_PRASSWORD)) {
			request.setAttribute("msg", "由于您的密码过于简单，为了账户安全，请重置密码！");
			String forward = "/portal.do?do=Register.mobile&t=r&msg="
					+ Functions.encode("由于您的密码过于简单，为了账户安全，请重置密码！");
			return new ActionForward(forward, true);
		}

		if (result.equals(SSOUtil.LOGIN_FAILURE_N_REG)) {
			request.setAttribute("msg", "此账号还未注册，请选择注册！");
			return action.display(request, response, "login");
		}

		if (result.equals(SSOUtil.LOGIN_FAILURE_NOEXIST)
				|| result.equals(SSOUtil.LOGIN_FAILURE)) {
			passwd_add(account);
			request.setAttribute("msg", "帐号或密码错误！");

			return action.display(request, response, "login");
		}
		String go = request.getParameter("go");
		if(StringUtils.isNotEmpty(go)) return new ActionRedirect(url(request, "portal.do", "do=Portal.login"));
		return new ActionRedirect(url(request, "portal.do", "do=Portal.my"));
	}

	/*
	 * 退出
	 */
	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {

		// 清空sso
		request.removeAttribute("SSO");
		// 清空cookie
		CookieUtil.clearAuth(response);

		String go = request.getParameter("go");
		if (go != null && go.length() > 3) {
			return new ActionForward(go, true);
		}

		return layout(mapping, form, request, response, action);
	}

	/**
	 * 登录后进的首页
	 */
	public ActionForward home(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		if (!isLogin(request)) {
			return action.display(request, response, "login");
		}

		return action.display(request, response, "home");
	}

	/**
	 * 登录成功(我的首页)
	 */
	public ActionForward my(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		if (!isLogin(request)) {
			return action.display(request, response, "login");
		}

		Integer username = u(request);
		Integer status = getUserState(username);
		if (status.equals(UserAccount.STATUS_DELETE)) {
			request.setAttribute("msg", "该用户还未注册！");
			return action.display(request, response, "info");
		}

		if (status.equals(UserAccount.STATUS_OFF)) {
			request.setAttribute("msg", "该用户已经被注销！");
			return action.display(request, response, "info");
		}

		String protect = getUserProtected(username);
		if (StringUtils.isBlank(protect)) {
			request.setAttribute("msg", "您尚未设置密码找回邮箱");
		}

		UserBasic user = user(request);
		request.setAttribute("cuser", user);

		List<Integer> categories = getCategoriesBySubscript(username);
		if (categories != null && categories.size() > 0) {
			String city = user.getCity();
			ActivityBiz biz = (ActivityBiz) SpringHelper.getBean("ActivityBiz");

			int totalRows = 0;
			String s = request.getParameter("n");
			if (s != null && !"".equals(s)) {
				totalRows = Integer.parseInt(s);
			} else {
				totalRows = biz.getMActivitiesByCcCount(city, categories,
						ActivityInfo.EXPIRE_ALL);
			}

			if (totalRows == 0) {
				return action.display(request, response, "my");
			}

			Pager pager = PagerHelper.getPager(request, totalRows, 10);
			List<ActivityAreaCategory> result = biz.getMActivitiesByCc(city,
					categories, ActivityInfo.EXPIRE_ALL, pager);

			request.setAttribute("result", result);
			request.setAttribute("pager", pager);
			request.setAttribute("baseLink", "&amp;do=Portal.my");
		}

		return action.display(request, response, "my");
	}

	/**
	 * 用户状态
	 *
	 * @param username
	 * @return
	 */
	private Integer getUserState(Integer username) {
		CoreBiz biz = (CoreBiz) SpringHelper.getBean("CoreBiz");
		Integer status = biz.getUserState(username);
		return status;
	}

	/**
	 * 获取用户订阅分类
	 *
	 * @param username
	 * @return
	 */
	private List<Integer> getCategoriesBySubscript(Integer username) {
		UserBiz ubiz = (UserBiz) SpringHelper.getBean("UserBiz");
		List<Integer> ret = ubiz.getSubscript(username);

		return ret;
	}

	/**
	 * 获取用户订阅分类
	 *
	 * @param username
	 * @return
	 */
	private String getUserProtected(Integer username) {
		UserBiz biz = (UserBiz) SpringHelper.getBean("UserBiz");
		return biz.getUserProtectEmail(username);
	}

	/*
	 *
	 */
	public ActionForward duplicate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {

		return action.display(request, response, "r/duplicate");
	}

	/*
	 *
	 */
	public ActionForward mobile(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {

		return action.display(request, response, "r/mobile");
	}

	/*
	 * 返回
	 */
	public ActionForward back(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {

		String forward = request.getParameter("go");
		if (forward != null && forward.length() > 3) {
			forward = forward.replaceAll("&amp;", "&");
			response.sendRedirect(forward);
			return null;
		}

		return my(mapping, form, request, response, action);
	}

	private int passwd_fail(String mobile) {
		if (mobile == null || mobile.length() == 0) {
			return -1;
		}
		IMemcachedCache cache = (IMemcachedCache) SpringHelper
				.getBean("FastMemcachedCache");
		String key = Functions.KEY_PASSWORD_FAIL + mobile;
		Object obj = cache.get(key);
		if (obj != null) {
			if (obj instanceof Integer) {
				return (Integer) obj;
			} else {
				cache.delete(key);
			}
		}

		return 0;
	}

	private int passwd_add(String mobile) {
		if (mobile == null || mobile.length() == 0) {
			return -1;
		}
		IMemcachedCache cache = (IMemcachedCache) SpringHelper
				.getBean("FastMemcachedCache");
		String key = Functions.KEY_PASSWORD_FAIL + mobile;
		Object obj = cache.get(key);
		Integer ret = 1;
		if (obj != null) {
			if (obj instanceof Integer) {
				ret = (Integer) obj;
				ret += 1;
			} else {
				cache.delete(key);
			}
		}

		cache.add(key, ret, Functions.HOUR * 2);

		return ret;
	}

	@SuppressWarnings("unused")
	private void passwd_delete(String mobile) {
		if (mobile == null || mobile.length() == 0) {
			return;
		}
		IMemcachedCache cache = (IMemcachedCache) SpringHelper
				.getBean("FastMemcachedCache");
		String key = Functions.KEY_PASSWORD_FAIL + mobile;

		cache.delete(key);
	}
}
